<template>
  <view class="withdraw">
    <view class="header" :style="
        'line-height:' +
        height +
        'px;height:' +
        height +
        'px;' +
        'padding-top:' +
        top +
        'px;padding-bottom:10rpx'
      ">
      <!-- <text style="flex:1;color:#333;position:absolute;left:20px" @click="back">返回</text> -->
      <text style="position: absolute;width: 120rpx; color: #333">返回</text>
      <text style="flex: 1; color: #333">合伙人合作协议</text>
    </view>
    <view class="sign">
      <view class="sign-1" @tap="back">
        取消
      </view>
      <view class="sign-2" @tap="sign">
        去签名
      </view>
    </view>
    <view class="modal" v-show="showSign">
      <canvas class="firstCanvas" canvas-id="firstCanvas" @touchmove="move" @touchstart="start($event)" @touchend="end"
        @touchcancel="cancel" @longtap="tap" disable-scroll="true" @error="error">
      </canvas>
      <view class="caozuo">
        <view class="chongqian" @tap="clearClick"> 重签 </view>
        <view class="over" @tap="overSign"> 完成签名 </view>
      </view>
    </view>
    <r-canvas ref="rCanvas1" style="position: absolute; top: -20000rpx; left: -20000rpx"></r-canvas>
    <r-canvas ref="rCanvas2" style="position: absolute; top: -20000rpx; left: -20000rpx"></r-canvas>
    <r-canvas ref="rCanvas3" style="position: absolute; top: -20000rpx; left: -20000rpx"></r-canvas>
    <r-canvas ref="rCanvas4" style="position: absolute; top: -20000rpx; left: -20000rpx"></r-canvas>
    <r-canvas ref="rCanvas5" style="position: absolute; top: -20000rpx; left: -20000rpx"></r-canvas>
    <r-canvas ref="rCanvas6" style="position: absolute; top: -20000rpx; left: -20000rpx"></r-canvas>
    <view class="contract" ref="contract">
      <image v-for="(imgObj, index) in imageList" :key="index" :style="'height:' + imgObj.height + 'rpx'"
        style="width: 100vw" :src="imgObj"></image>
    </view>
    <view class="loading" v-show="loading">
      <view class="loading-mask"></view>
      <view class="loading-content">
        <view style="margin: 0 95upx;">正在生成中,请稍候，谢谢...</view>
      </view>
    </view>
  </view>
</template>

<script>
  var content = null;
  var touchs = [];
  var canvasw = 0;
  var canvash = 0;
  uni.getSystemInfo({
    success: function(res) {
      canvasw = res.windowWidth;
      canvash = res.windowHeight;
    },
  });
  import rCanvas from "@/components/r-canvas/r-canvas.vue";
  export default {
    components: {
      rCanvas,
    },
    data() {
      return {
        top: "",
        height: "",
        showSign: false,
        imageList: [],
        locationList: [],
        loading: false,
        signImage: '',
        userSignImg: '',
        contractSignIndex: 0,
        contractImgArr: [],
        contractSignArr: []
      };
    },
    onLoad(options) {

    },
    onShow() {
      let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
      this.height = menuButtonInfo.height;
      this.top = menuButtonInfo.top;
      this.getContractImg();
    },

    methods: {
      async insec(imgurl) {
        this.$nextTick(async () => {
            // 初始化
            await this.$refs.rCanvas1.init({
              canvas_id: "rCanvas1",
              canvas_height: this.locationList[0],
            });
            // 画图
            await this.$refs.rCanvas1
              .drawImage({
                url: this.imageList[0],
                x: 0,
                y: 0,
                w: 730,
                h: this.locationList[0],
              })
              .catch((err_msg) => {
                uni.showToast({
                  title: err_msg,
                  icon: "none",
                });
              });
            await this.$refs.rCanvas1.drawText({
              text: '12312312',
              max_width: 0,
              x: 380,
              y: 140,
              font_color: "rgb(0,0,0)",
              font_weight: "bold",
              font_size: 20,
            });
            await this.$refs.rCanvas1.draw((res) => {
              //res.tempFilePath：生成成功，返回base64图片
              console.log(1);
              this.contractImgArr.push(res.tempFilePath);
            });
            // 222222222
            await this.$refs.rCanvas2.init({
              canvas_id: "rCanvas2",
              canvas_height: this.locationList[1],
            });
            await this.$refs.rCanvas2
              .drawImage({
                url: this.imageList[1],
                x: 0,
                y: 0,
                w: 730,
                h: this.locationList[1],
              })
              .catch((err_msg) => {
                uni.showToast({
                  title: err_msg,
                  icon: "none",
                });
              });
              await this.$refs.rCanvas2
              .drawImage({
                url: imgurl,
                x: 100,
                y: 100,
                w: 375,
                h: 500,
              })
              .catch((err_msg) => {
                uni.showToast({
                  title: err_msg,
                  icon: "none",
                });
              });
            await this.$refs.rCanvas2.draw((res) => {
              //res.tempFilePath：生成成功，返回base64图片
              console.log(12);
              this.contractImgArr.push(res.tempFilePath);
            });
            // 333333
            // await this.$refs.rCanvas3.init({
            //   canvas_id: "rCanvas3",
            //   canvas_height: this.imageList[2].height,
            // });
            // await this.$refs.rCanvas3
            //   .drawImage({
            //     url: this.imageList[2].img_id,
            //     x: 0,
            //     y: 0,
            //     w: 730,
            //     h: this.imageList[2].height,
            //   })
            //   .catch((err_msg) => {
            //     uni.showToast({
            //       title: err_msg,
            //       icon: "none",
            //     });
            //   });


            // await this.$refs.rCanvas3.draw((res) => {
            //   //res.tempFilePath：生成成功，返回base64图片
            //   console.log(123);
            //   this.contractImgArr.push(res.tempFilePath);
            // });

            // // 444444
            // await this.$refs.rCanvas4.init({
            //   canvas_id: "rCanvas4",
            //   canvas_height: this.imageList[3].height,
            // });
            // await this.$refs.rCanvas4
            //   .drawImage({
            //     url: this.imageList[3].img_id,
            //     x: 0,
            //     y: 0,
            //     w: 730,
            //     h: this.imageList[3].height,
            //   })
            //   .catch((err_msg) => {
            //     uni.showToast({
            //       title: err_msg,
            //       icon: "none",
            //     });
            //   });
            // await this.$refs.rCanvas4.drawText({
            //   text: this.other,
            //   max_width: 0,
            //   x: 550,
            //   y: 345,
            //   // y: 5370 - this.imageList[0].height - this.imageList[1].height,
            //   font_color: "rgb(0,0,0)",
            //   font_weight: "bold",
            //   font_size: 20,
            // });
            // await this.$refs.rCanvas4.drawText({
            //   text: this.signDate,
            //   max_width: 0,
            //   x: 580,
            //   y: 425,
            //   // y: 5430 - this.imageList[0].height - this.imageList[1].height,
            //   font_color: "rgb(0,0,0)",
            //   font_weight: "bold",
            //   font_size: 20,
            // });
            // await this.$refs.rCanvas4
            //   .drawImage({
            //     url: imgurl,
            //     x: 390,
            //     y: 10,
            //     // y: 4970 - this.imageList[0].height - this.imageList[1].height,
            //     w: 375,
            //     h: 500,
            //   })
            //   .catch((err_msg) => {
            //     uni.showToast({
            //       title: err_msg,
            //       icon: "none",
            //     });
            //   });
            // await this.$refs.rCanvas4.drawText({
            //   text: this.other,
            //   max_width: 0,
            //   x: 520,
            //   y: 2500,
            //   font_color: "rgb(0,0,0)",
            //   font_weight: "bold",
            //   font_size: 20,
            // });
            // await this.$refs.rCanvas4.drawText({
            //   text: this.signDate,
            //   max_width: 0,
            //   x: 520,
            //   y: 2580,
            //   font_color: "rgb(0,0,0)",
            //   font_weight: "bold",
            //   font_size: 20,
            // });
            // await this.$refs.rCanvas4
            //   .drawImage({
            //     url: imgurl,
            //     x: 380,
            //     y: 2150,
            //     w: 375,
            //     h: 500,
            //   })
            //   .catch((err_msg) => {
            //     uni.showToast({
            //       title: err_msg,
            //       icon: "none",
            //     });
            //   });
            // await this.$refs.rCanvas4.draw((res) => {
            //   //res.tempFilePath：生成成功，返回base64图片
            //   this.contractImgArr.push(res.tempFilePath);
            // });

            // // 55555555
            // await this.$refs.rCanvas5.init({
            //   canvas_id: "rCanvas5",
            //   canvas_height: this.imageList[4].height,
            // });
            // await this.$refs.rCanvas5
            //   .drawImage({
            //     url: this.imageList[4].img_id,
            //     x: 0,
            //     y: 0,
            //     w: 730,
            //     h: this.imageList[4].height,
            //   })
            //   .catch((err_msg) => {
            //     uni.showToast({
            //       title: err_msg,
            //       icon: "none",
            //     });
            //   });
            // await this.$refs.rCanvas5.draw((res) => {
            //   //res.tempFilePath：生成成功，返回base64图片
            //   console.log(12345);
            //   this.contractImgArr.push(res.tempFilePath);
            // });

            // // 666666
            // await this.$refs.rCanvas6.init({
            //   canvas_id: "rCanvas6",
            //   canvas_height: this.imageList[5].height,
            // });
            // await this.$refs.rCanvas6
            //   .drawImage({
            //     url: this.imageList[5].img_id,
            //     x: 0,
            //     y: 0,
            //     w: 730,
            //     h: this.imageList[5].height,
            //   })
            //   .catch((err_msg) => {
            //     uni.showToast({
            //       title: err_msg,
            //       icon: "none",
            //     });
            //   });
            // await this.$refs.rCanvas6.draw((res) => {
            //   //res.tempFilePath：生成成功，返回base64图片
            //   console.log(123456);
            //   this.contractImgArr.push(res.tempFilePath);
            // });
            this.saveContract()
        });
      },
      saveContract() {
        let _this = this;
        uniCloud.uploadFile({
          filePath: _this.contractImgArr[_this.contractSignIndex],
          cloudPath: new Date().getTime() + ".jpg",
          success(res) {
            _this.contractSignArr.push(res.fileID);
            _this.contractSignIndex++;
            if (_this.contractSignIndex < _this.contractImgArr.length) {
              _this.saveContract();
            } else {
              // console.log(_this.contractSignArr);
              _this.doneContract();
              _this.loading = false
            }
          },
        });
      },
      async doneContract() {
       // 真正的上传合同
      },
      async getContractImg() {
        let info = await this.vk.callFunction({
          url: 'user/pub/templateList',
          data: {
            _id: '652e00c9213929cbce26b166'
          },
          title: "请求中...",
        });
        if (info.code == 0) {
          this.imageList = info.rows[0].imageList
          this.locationList = info.rows[0].locationList.split(',')
        }
      },
      back() {
        uni.switchTab({
          url: "/pages/my/my",
        });
      },
      sign() {
        let _this = this;
        uni.showModal({
          title: "提示",
          content: "您已阅读并同意协议，点击确定开始手写签名",
          success: function(res) {
            if (res.confirm) {
              content = wx.createCanvasContext("firstCanvas");
              //设置线的颜色
              content.setStrokeStyle("#000");
              //设置线的宽度
              content.setLineWidth(5);
              //设置线两端端点样式更加圆润
              content.setLineCap("round");
              //设置两条线连接处更加圆润
              content.setLineJoin("round");
              _this.showSign = true;
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      },
      overSign: function() {
        let _this = this;
        if (this.isEnd) {
          uni.canvasToTempFilePath({
            canvasId: "firstCanvas",
            success: function(res) {
              //打印图片路径
              console.log(res.tempFilePath);
              console.log("完成签名");
              //设置图片
              _this.signImage = res.tempFilePath;
              _this.showSign = false;
              _this.loading = true;
              uniCloud.uploadFile({
                filePath: res.tempFilePath,
                cloudPath: new Date().getTime() + ".jpg",
                success(res) {
                  _this.userSignImg = res.fileID;
                  _this.insec(res.fileID);
                  _this.clearClick();
                },
              });
            },
          });
        } else {
          uni.showToast({
            title: "请先完成签名",
            icon: "none",
            duration: 1500,
            mask: true,
          });
        }
      },
      // 画布的触摸移动开始手势响应
      start: function(event) {
        // console.log(event)
        console.log("触摸开始" + event.changedTouches[0].x);
        console.log("触摸开始" + event.changedTouches[0].y);
        //获取触摸开始的 x,y
        let point = {
          x: event.changedTouches[0].x,
          y: event.changedTouches[0].y,
        };
        // console.log(point)
        touchs.push(point);
      },
      // 画布的触摸移动手势响应
      move: function(e) {
        let point = {
          x: e.touches[0].x,
          y: e.touches[0].y,
        };
        // console.log(point)
        touchs.push(point);
        if (touchs.length >= 2) {
          this.draw(touchs);
        }
      },

      // 画布的触摸移动结束手势响应
      end: function(e) {
        console.log("触摸结束" + e);
        // 设置为已经签名
        this.isEnd = true;
        // 清空轨迹数组
        for (let i = 0; i < touchs.length; i++) {
          touchs.pop();
        }
      },
      // 画布的触摸取消响应
      cancel: function(e) {
        console.log("触摸取消" + e);
      },
      // 画布的长按手势响应
      tap: function(e) {
        console.log("长按手势" + e);
      },
      error: function(e) {
        console.log("画布触摸错误" + e);
      },
      //绘制
      draw: function(touchs) {
        console.log(touchs[0], touchs[1]);
        let point1 = touchs[0];
        let point2 = touchs[1];
        touchs.shift();
        content.moveTo(point1.x, point1.y);
        content.lineTo(point2.x, point2.y);
        content.stroke();
        content.setFillStyle("#fff");
        content.draw(true);
      },
      //清除操作
      clearClick: function() {
        // 设置为未签名
        this.isEnd = false;
        //清除画布
        content.clearRect(0, 0, canvasw, canvash);
        content.draw(true);
      },
    },
  };
</script>

<style lang="scss">
  page {
    height: 100% !important;
  }

  .loading {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    width: 100vw;
    z-index: 10;

    &-mask {
      height: 100vh;
      width: 100vw;
      background: rgba(0, 0, 0, 0.6);
      position: absolute;
      left: 0;
      top: 0;
      z-index: 20;
    }

    &-content {
      position: absolute;
      background: #eee;
      border-radius: 8upx;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 21;
      width: 600upx;
      height: 300upx;
      display: flex;
      // align-items: center;
      justify-content: center;
      flex-direction: column;
    }

    .loading-content {
      text {
        margin-left: 10upx;
        color: #E96B00;
        font-size: 36upx;
      }

      .wait-txt {
        font-size: 28upx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #000000;
        height: 40upx;
        line-height: 72upx;
        letter-spacing: 2upx;
        margin: 0 95upx;
      }
    }
  }

  .sign {
    position: fixed;
    bottom: 0;
    left: 0;
    background: #fff;
    display: flex;
    justify-content: space-around;
    align-items: center;
    width: 100%;
    height: 120upx;
    z-index: 22;
    text-align: center;
    line-height: 120upx;
    &-1 {
      background-color: #ccc;
      color: #fff;
      flex:1;
    }
    &-2 {
      background: #0599d7;
      color:#fff;
      flex:1;
    }
  }

  .modal {
    position: fixed;
    left: 0;
    bottom: 0;
    height: 100vh;
    width: 100vw;
    z-index: 101;
    background-color: #dddddd;

    canvas {
      width: 100%;
      height: calc(100% - 100rpx);
    }
  }

  .caozuo {
    display: flex;
    height: 100upx;
    width: 750upx;
    position: fixed;
    z-index: 101;
    left: 0;
    bottom: 0;
  }

  .caozuo view {
    width: 375upx;
    text-align: center;
    height: 100upx;
    line-height: 100upx;
    color: #ffffff;
  }

  .caozuo view:active {
    background-color: #cccccc;
    color: #333333;
  }

  .chongqian {
    background-color: #ff8f58;
  }

  .over {
    background-color: #0599d7;
  }

  .withdraw {
    height: 100%;
    position: relative;

    .header {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      z-index: 101;
      font-size: 32upx;
      color: #999;
      line-height: 45upx;
      text-align: center;
      background: #c3c3c3;
      display: flex;
      align-items: center;

      image {
        width: 38upx;
        height: 48upx;
        position: absolute;
        left: 20upx;
      }
    }

    .contract {
      width: 100%;
      height: auto;
      padding-bottom: 140upx;
      background: #fff;
      margin-top: 120upx;
      font-size: 22upx;
      line-height: 40upx;

      .center {
        text-align: center;
      }

      .text-indent {
        text-indent: 20upx;
      }

      .font-bold {
        font-weight: bold;
      }

      .text1 {
        font-size: 24upx;
        font-weight: bold;
      }
    }
  }
</style>